package it.pride.primefacesShowcase.controller;

import it.pride.primefacesShowcase.filters.DateInterval;
import it.pride.primefacesShowcase.filters.Filter;
import it.pride.primefacesShowcase.filters.Like;
import it.pride.primefacesShowcase.service.UserService;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

/**
 * Created by IntelliJ IDEA.
 * User: lbonacina
 * Date: 4-nov-2010
 * Time: 17.26.58
 */
@Controller(value = "extLazyDatatable")
@Scope("session")
public class ExtLazyDatatableController {

    private static Logger logger = Logger.getLogger(ExtLazyDatatableController.class.getName());

    @Autowired
    private UserService userService;

    private ExtUserLazyDataModel usersLazyDataModel;
    
    // custom filters on datatable headers
    private String lastName;
    private Date birthDateFrom;
    private Date birthDateTo;

    public void init() {
        usersLazyDataModel = new ExtUserLazyDataModel();
        usersLazyDataModel.init(userService);
    }

    public ExtUserLazyDataModel getUsersLazyDataModel() {
        return usersLazyDataModel;
    }

    public void setUsersLazyDataModel(ExtUserLazyDataModel usersLazyDataModel) {
        this.usersLazyDataModel = usersLazyDataModel;
    }

    public Date getBirthDateFrom() {
        return birthDateFrom;
    }

    public void setBirthDateFrom(Date birthDateFrom) {
        this.birthDateFrom = birthDateFrom;
    }

    public Date getBirthDateTo() {
        return birthDateTo;
    }

    public void setBirthDateTo(Date birthDateTo) {
        this.birthDateTo = birthDateTo;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public void doFilter() {

        logger.debug("Selected Birth Date From : " + birthDateFrom);
        logger.debug("Selected Birth Date To : " + birthDateTo);        
        logger.debug("Selected Last Name To : " + lastName);
        
        List<Filter> additionalFilters = new ArrayList<Filter>() ;
        
        if ( (birthDateFrom != null) || (birthDateTo != null) ) {
            additionalFilters.add(new DateInterval("birthDate", birthDateFrom, birthDateTo));
        }
        
        if ((lastName != null) && (!lastName.equals(""))) {
            additionalFilters.add(new Like("lastName", lastName));
        }
        
        // add additional filters to Lazy Datamodel
        usersLazyDataModel.setAdditionalFilters(additionalFilters);
    }
}
